package com.heima.juc.n4;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;

/**
 * @author : leimingchao
 * @date Date : 2022年01月11日 20:54
 */
@Slf4j(topic = "c.ExerciseSell")
public class ExerciseSell {

    /**
     * Random为线程安全
     */
    static Random random = new Random();

    /**
     * 随机 1~5
     * @return
     */
    public static int randomAmount() {
        return random.nextInt(5) + 1;
    }

    public static void main(String[] args) {
        //模拟多人买票
        TicketWindow ticketWindow = new TicketWindow(1000);
        List<Integer> amountList = new Vector<>();
        //所有线程的集合
        List<Thread> threadList = new ArrayList<>();
        for (int i = 0; i < 4000; i++) {
            Thread thread = new Thread(() -> {
                int amount = ticketWindow.sell(randomAmount());
                amountList.add(amount);
            });
            threadList.add(thread);
            thread.start();
        }

        threadList.stream().forEach(item -> {
            try {
                item.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        //统计卖出的票数和剩余的票数
        log.debug("余票数量：{}",ticketWindow.getCount());
        log.debug("卖出去票数：{}",amountList.stream().mapToInt(Integer::intValue).sum());

    }
}


class TicketWindow {

    private int count;

    public TicketWindow(int count) {
        this.count = count;
    }

    /**
     * 获取余票数量
     * @return
     */
    public int getCount() {
        return count;
    }

    public synchronized int sell(int amount) {
        if (this.count >= amount) {
            this.count -=amount;
            return amount;
        } else {
            return 0;
        }
    }
}
